package com.yytek.job.task;

import cn.hutool.core.collection.CollectionUtil;
import com.yytek.common.core.domain.*;
import com.yytek.nmp.api.RemoteNmpService;
import com.yytek.nmp.api.RemoteUpgradeService;
import com.yytek.nmp.api.domain.UpgradeStrategy;
import com.yytek.nmp.api.domain.UpgradeStrategyDeviceTopo;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.util.List;


/**
 * 设备升级任务
 */
@Component("upGrade")
public class UpgradeTask
{
    @Resource
    private RemoteNmpService remoteNmpService;
    @Resource
    private RemoteUpgradeService remoteUpgradeService;

    /**
     * 设备升级任务
     * @param upgradeStrategyId 升级策略id
     */
    public void strategy(String upgradeStrategyId)
    {
        //获取升级策略
        R<UpgradeStrategy> upgradeStrategyR = remoteUpgradeService.getUpgradeStrategy(Long.valueOf(upgradeStrategyId));

        if(upgradeStrategyR != null && upgradeStrategyR.getData() != null){
            UpgradeStrategy upgradeStrategy = upgradeStrategyR.getData();
            //获取策略的所有绑定设备信息
            R<List<UpgradeStrategyDeviceTopo>> result = remoteUpgradeService.getBindDeviceTopo(Long.valueOf(upgradeStrategyId));
            if(result != null && result.getData() != null){
                List<UpgradeStrategyDeviceTopo> upgradeStrategyDeviceTopos = result.getData();
                //循环发送设备升级信息
                if(CollectionUtil.isNotEmpty(upgradeStrategyDeviceTopos)){
                    for (int i = 0; i < upgradeStrategyDeviceTopos.size(); i++) {
                        String iotId = upgradeStrategyDeviceTopos.get(i).getDeviceId();
                        //发送设备升级服务调用信息
                        remoteNmpService.sendDeviceUpgradeMsg(iotId,upgradeStrategyId);
                        //发送完成后更新设备升级记录状态[执行状态(0:未执行,1:执行中,2:成功,3:失败,4:超时,5:操作冲突)]
                        remoteUpgradeService.changeStrategyHisStatus(iotId,upgradeStrategy.getId(),1);
                    }
                }
            }
        }

    }


}
